package it.softphone.cmc;

import it.softphone.cmc.shared.entity.EntityFactory;
import it.softphone.cmc.shared.entity.TenantUser;
import it.softphone.commons.util.Util;

import java.io.IOException;
import java.util.Iterator;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.vm.AutoBeanFactorySource;

public class CMCManager {

	/**
	 * @param args
	 */
	@SuppressWarnings("static-access")
	public static void main(String[] args) throws Exception {
		final EntityFactory ef = AutoBeanFactorySource.create( EntityFactory.class );

		CommandLineParser parser = new GnuParser();
		
		Options options = new Options();
		
		Option help = new Option( "help", "print this message" );

		options.addOption(help);		

		OptionBuilder.withArgName( "username" )
								.hasArg()
								.withDescription( "account's username");
		options.addOption(OptionBuilder.create( "u" ));		

		OptionBuilder.withArgName( "password" )
								//.isRequired()
								.hasArg()
								.withDescription( "account's password");
		options.addOption(OptionBuilder.create( "p" ));		
		
		OptionBuilder
			.withArgName( "url" )
			.hasArg()
			.withDescription( "cmc url - default http://conv-mobile-mgr.appspot.com");		
		options.addOption(OptionBuilder.create( "url" ));		
		
		OptionBuilder
			.withArgName( "scriptdir" )
			.hasArg()
			.withDescription( "scriptlet folder. default:[./scripts]");
		options.addOption(OptionBuilder.create("scriptdir"));	
		
		OptionBuilder
			.withArgName( "script" )
			.hasArg()
			.withDescription( "remote scriptlet execution");
		options.addOption(OptionBuilder.create("execscript"));		
		OptionBuilder
			.withArgName( "script" )
			.hasArg()
			.withDescription( "save scriptlet to host");
		options.addOption(OptionBuilder.create("savescript"));		
		OptionBuilder
			.withArgName( "script" )
			.hasArg()
			.withDescription( "save jasonware scriptlet to host");
		options.addOption(OptionBuilder.create("savejsons"));		

		options.addOption("adduser", false, "add new user");
		options.addOption("reguser", false, "register user (account creation)");

		options.addOption("newaccount", false, "add a new account");
		
		CMCServiceManager service = new CMCServiceManager();
		
		try {
			String logo = Util.toString( new java.io.InputStreamReader(CMCManager.class.getClassLoader().getResourceAsStream("logo.txt"))) ;
			
			System.out.println( logo );
			
			CommandLine cmdLine = parser.parse(options, args);
			
			if( cmdLine.hasOption("help")) {
				
				help( options );
				return;
			}
			
			
			if( cmdLine.hasOption("u")) {
				
				service.setUsername(cmdLine.getOptionValue("u"));
				
			}
			if( cmdLine.hasOption("p")) {
				
				service.setPassword(cmdLine.getOptionValue("p"));
				
			}
			if( cmdLine.hasOption("url")) {
				
				service.setBaseUrl(cmdLine.getOptionValue("url"));
				
			}
			else {
				service.setBaseUrl("http://conv-mobile-mgr.appspot.com");
				
			}
			
			java.io.File scriptPath;
			
			if( cmdLine.hasOption("scriptdir")) {
				
				scriptPath = new java.io.File(cmdLine.getOptionValue("scriptdir") );
			}
			else {
				scriptPath = new java.io.File("./scripts");				
			}
			
			if( cmdLine.hasOption("savescript")) {
				
				System.out.println( service );
				
				service.init();
				//final String scriptName = cmdLine.getOptionValue("savescript");
				//java.io.File f = new java.io.File( scriptPath, scriptName.concat(".js") );

				//service.scriptletService.saveScript( scriptName, "undef", new java.io.FileReader(f) );
				return;
			}
			if( cmdLine.hasOption("savejsons")) {
				
				System.out.println( service );
				
				service.init();
				final String scriptName = cmdLine.getOptionValue("savejsons");
				if( scriptName==null ) {
					System.err.println( "script name is null!");
					return;
				}
				//java.io.File f = new java.io.File( scriptPath, scriptName.concat(".js") );
				//service.scriptletService.saveScript( scriptName, Scriptlet.TYPE_JSON, new java.io.FileReader(f) );
				return;
				
			}
			if( cmdLine.hasOption("execscript")) {
				
				System.out.println( service );
				
				service.init();
				//service.scriptletService.execScript(cmdLine.getOptionValue("execscript"), new MultivaluedMapImpl());

				return;

			}
			if( cmdLine.hasOption("adduser")) {
				
				System.out.println( service );
				
				service.init();

				AutoBean<TenantUser> bean = ef.makeUser();
				
				it.softphone.commons.json.server.JSONObject u = new it.softphone.commons.json.server.JSONObject( bean.as() );
				
				Iterator<String> names = u.sortedKeys();
				
				java.io.LineNumberReader nr = new java.io.LineNumberReader( new java.io.InputStreamReader(System.in) );
				while( names.hasNext() ) {
					
					String n = names.next();
					Object o = u.get(n);
					System.out.printf( "%s [%s]:", n, String.valueOf(o) );
					String value = nr.readLine();
					if( !value.isEmpty() )
						u.put(n, value);

				}
				
				System.out.println( "====== USER =======");
				System.out.println( u.toString(3));
				System.out.print( "confirm add ? (y/n)");
				char c = (char)System.in.read();
				
				if( 'y' == Character.toLowerCase(c) ) {
					service.createUser(u);
					System.out.println( "user created!");
				}
				return;

			}
			if( cmdLine.hasOption("reguser")) {
				
				System.out.println( service );
				
				service.init();

				it.softphone.commons.json.server.JSONObject u = 
					new it.softphone.commons.json.server.JSONObject()
						.putObject("tenantId", "")
						.putObject("userId", "")
						.putObject( "passwd", "")
						.putObject( "deviceId", "")
						.putObject( "name", "")
						;
				
				Iterator<String> names = u.sortedKeys();
				
				java.io.LineNumberReader nr = new java.io.LineNumberReader( new java.io.InputStreamReader(System.in) );
				while( names.hasNext() ) {
					
					String n = names.next();
					Object o = u.get(n);
					System.out.printf( "%s [%s]:", n, String.valueOf(o) );
					String value = nr.readLine();
					if( !value.isEmpty() )
						u.put(n, value);

				}
				
				System.out.println( "====== REGISTRATION =======");
				System.out.println( u.toString(3));
				System.out.print( "confirm registration ? (y/n)");
				char c = (char)System.in.read();
				
				if( 'y' == Character.toLowerCase(c) ) {
					service.registerUser(u);
					System.out.println( "user registered!");
				}
				return;

			}
			
			
		} catch (ParseException e) {
			System.err.println("command line error");
			System.err.println();
			e.printStackTrace();
		} catch (IOException e) {
			// TODO log
			e.printStackTrace();
		}
	}

	private static void help( Options options ) {

		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp( "cmcadmin", options );	}

}
